require 'rubygems'
require 'mysql'
require 'singleton'
require 'ERB'

class DBHelp
	include Singleton  
	
	def initialize
		@dbh = Mysql.init
		@dbh.options(Mysql::SET_CHARSET_NAME, 'utf8')
		taobao_config_file = File.dirname(__FILE__) + '/../config/database.yml'
		config = YAML.load(ERB.new(File.read(taobao_config_file)).result)
		#@dbh = Mysql.real_connect(config['host'], config['username'], config['password'],config['database'], 3306) #连接数据库
		@dbh = Mysql.real_connect('localhost', 'root', 'admin','ladyshop', 3306) #连接数据库
		@dbh.query("SET NAMES utf8")
	end
	
	def query(sql)
		begin
		  puts sql  
			@dbh.query(sql)
		rescue Mysql::Error=>e
			puts "Error code:#{e.errno}"
		end
	end
	
	def build_sql(hash = {})
		fields = ""
		values = ""
		i = 0
		hash.each_pair do |key, value|
			next if key.to_s == "table"
		  i += 1
			fields += key.to_s
			fields += ", " unless i == hash.length - 1
			values += "'#{value.to_s}'"
			values += ", " unless i == hash.length - 1
		end
		sql = "insert into #{hash['table']} ("
		sql += fields + ") "
		sql += "values (" + values + ")"
	end
	
	def close
		@dbh.close if @dbh 
	end
end
